<template>
  <div class="Blockeywords">
    <el-card shadow="hover">
      <div class="searchBox">
        <div>
          <el-input placeholder="请输入过滤词" v-model="filterWords">
            <template slot="prepend">过滤词</template>
          </el-input>
          <el-button class="btn" @click="keywordKeywordListBtn"
            >查找搜索</el-button
          >
        </div>
        <div class="addBox">
          <span
            >本次新增：<span class="bold">{{ count }}</span> 条</span
          >
          <span style="margin: 0 20px"
            >累积条数：<span class="bold">{{ totalNum }}</span> 条</span
          >
          <el-button class="btn" @click="dialogVisible = true"
            >新增过滤词</el-button
          >
          <!-- <el-button class="btn" >导出过滤词表</el-button> -->
        </div>
      </div>
      <el-table
        ref="multipleTable"
        :data="tableData"
        v-loading="loading"
        tooltip-effect="dark"
        style="width: 100%"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55"> </el-table-column>
        <el-table-column label="过滤词">
          <template slot-scope="scope">{{ scope.row.keyword }}</template>
        </el-table-column>
        <el-table-column prop="address" label="操作" show-overflow-tooltip>
          <template slot-scope="scope">
            <el-button size="mini" @click="handleEdit(scope.row)"
              >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>
      <div style="margin-top: 20px">
        <!-- <el-button @click="toggleSelection(tableData)"
          >切换第二、第三行的选中状态</el-button
        > -->
        <!-- <template slot-scope="scope"> -->
        <el-button
          @click="toggleSelection(tableData)"
          v-if="tableData.length > 0"
          >删除选中</el-button
        >
        <!-- </template> -->
      </div>
      <pagination
        v-show="total > 0"
        :total="total"
        :page.sync="page"
        :limit.sync="pageSize"
        @pagination="getList"
      />
    </el-card>
    <el-dialog title="新增过滤词" :visible.sync="dialogVisible" width="30%">
      <div class="dialogBox">
        <el-input placeholder="请输入内容" v-model="keywordSetkeywordInput">
          <template slot="prepend">输入过滤词</template>
        </el-input>
        <el-upload
          class="upload-demo"
          :http-request="upLoad"
          action
          :before-upload="beforeAvatarUpload"
          multiple
          :limit="3"
          :on-exceed="handleExceed"
          :file-list="fileList"
          ref="my-upload"
        >
          <el-button size="small" type="primary">点击上传文件</el-button>
          <!-- <div slot="tip" class="el-upload__tip">
            只能上传jpg/png文件，且不超过500kb
          </div> -->
        </el-upload>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="keywordSetkeywordBtn"
          >确 定</el-button
        >
      </span>
    </el-dialog>
  </div>
</template>

<script>
import Pagination from "@/components/Pagination"; // 分页
import {
  keywordKeywordList,
  keywordDel,
  keywordSetkeyword,
} from "@/api/operationManagement";
import { client } from "@/utils/oss.js";
import { ossToken } from "@/api/NotificationManagement";

export default {
  components: { Pagination },
  inject: ["reload"],
  data() {
    return {
      loading: true,
      filterWords: "",
      keywordSetkeywordInput: "", //ADD
      tableData: [],
      multipleSelection: [],
      total: 0,
      page: 1, //页码
      pageSize: 10, //每页条数
      dialogVisible: false,
      fileList: [],
      fileTxt: "",
      id_arr: [],
      count: 0,
      totalNum: 0,
    };
  },
  methods: {
    //列表
    keywordKeywordList() {
      this.loading = true;
      keywordKeywordList({
        keyWord: "",
        page: this.page,
        pageSize: this.pageSize,
      }).then((res) => {
        if (res.code == 0) {
          this.tableData = res.data.list;
          this.total = parseInt(res.data.count);
          this.totalNum = parseInt(res.data.total);
          this.loading = false;
        }
      });
    },
    //搜索
    keywordKeywordListBtn() {
      this.page = 1;
      this.loading = true;

      keywordKeywordList({
        keyword: this.filterWords,
        page: this.page,
        pageSize: this.pageSize,
      }).then((res) => {
        if (res.code == 0) {
          this.tableData = res.data.list;
          this.total = parseInt(res.data.count);
          this.loading = false;
        }
      });
    },
    //添加
    keywordSetkeywordBtn() {
      if (this.keywordSetkeywordInput || this.fileTxt !== "") {
        keywordSetkeyword({
          keywordSetkeyword: this.keywordSetkeywordInput,
          file: this.fileTxt,
        }).then((res) => {
          // console.log(res);

          if (res.code == 0) {
            this.$message({
              type: "success",
              message: "添加成功",
            });
            this.count = res.data.count;
            // this.reload();
            this.keywordSetkeywordInput = "";
            this.fileTxt = "";
            this.keywordKeywordList();
            this.$refs["my-upload"].clearFiles();
            this.dialogVisible = false;
          }
        });
      } else {
        this.$message({
          type: "info",
          message: "添加不能为空",
        });
      }
    },
    //删除
    handleEdit(row) {
      console.log(row);
      keywordDel({
        keyword: [row.keyword],
      }).then((res) => {
        if (res.code == 0) {
          this.$message({
            type: "success",
            message: "删除成功",
          });
          this.id_arr = [];
          this.getList();
        }
      });
    },
    //删除选中
    toggleSelection(rows) {
      if (this.id_arr.length == 0) {
        this.$message({
          type: "info",
          message: "请正确勾选",
        });
      } else {
        keywordDel({
          keyword: this.id_arr,
        }).then((res) => {
          if (res.code == 0) {
            this.$message({
              type: "success",
              message: "删除成功",
            });
            this.id_arr = [];
            this.$nextTick(() => {
              this.getList();
            });
          }
        });
      }
      // console.log(rows);
      // if (rows) {
      //   rows.forEach((row) => {
      //     console.log(row.id);
      //     var arr = []
      //     arr.push(row)
      //     console.log(arr);
      //     this.$refs.multipleTable.toggleRowSelection(row);

      // });
      // } else {
      //   this.$refs.multipleTable.clearSelection();
      // }
    },
    //选中
    handleSelectionChange(val) {
      this.multipleSelection = val;
      for (var i = 0; i < this.multipleSelection.length; i++) {
        var _i = this.multipleSelection[i].keyword;
        this.id_arr.push(_i);
      }
    },

    handleExceed(files, fileList) {
      this.$message.warning(
        `当前限制选择 3 个文件，本次选择了 ${files.length} 个文件，共选择了 ${
          files.length + fileList.length
        } 个文件`
      );
    },
    beforeAvatarUpload(file) {
      const isTXT = file.type === "text/plain";
      if (!isTXT) {
        this.$message.error("上传文件只能是 TXT 格式!");
      }
      return isTXT;
    },
    //覆盖默认的上传行为，自定义上传的实现
    async upLoad(file) {
      await ossToken({
        type: 7, //txt
      }).then((res) => {
        if (res.code == 0) {
          this.dataObj = {
            accessKeyId: res.data.accessKey,
            accessKeySecret: res.data.accessSecret,
            securityToken: res.data.token,
            // region: "oss-cn-shanghai",
            region: "oss-" + res.data.regionId,
            bucket: res.data.bucket,
          };
        }
      });
      const self = this;
      let files = file.file,
        point = files.name.lastIndexOf("."),
        suffix = files.name.substr(point),
        fileName = files.name.substr(0, point),
        date = Date.parse(new Date()),
        fileNames = "/other/" + file.file.name;
      this.fileTxt = fileNames;
      // this.fileList = fileNames;
      // console.log(fileNames);
      //fileNames上传文件的名称
      //file.file上传文件的内容
      client(this.dataObj)
        .multipartUpload(fileNames, file.file)
        .then((result) => {
          // console.log(this.dataObj);
          //下面是如果对返回结果再进行处理，根据项目需要
          // console.log(result);
          self.$message({
            message: "上传成功",
            type: "success",
          });
        })
        .catch((err) => {
          self.$message.error("上传失败");
        });
    },
    //分页
    getList() {
      this.loading = true;

      keywordKeywordList({
        keyword: this.filterWords,
        page: this.page,
        pageSize: this.pageSize,
      }).then((res) => {
        if (res.code == 0) {
          this.tableData = res.data.list;
          this.total = parseInt(res.data.count);
          this.loading = false;
        }
      });
    },
  },
  created() {
    this.keywordKeywordList();
  },
};
</script>

<style lang="less" >
.Blockeywords {
  margin: 30px;
  height: 100%;
  .searchBox {
    display: flex;
    justify-content: space-between;
    margin-bottom: 40px;
    div {
      display: flex;
      width: 50%;
      .el-input-group__prepend {
        width: 90px;
        line-height: 38px;
      }
      .el-input {
        margin-right: 10px;
      }
    }
    .addBox {
      display: flex;
      justify-content: flex-end;
      align-items: center;
      flex: 1;
      font-size: 20px;
      .bold {
        font-weight: bold;
        color: #f00;
      }
    }
  }
  .dialogBox {
    .el-input {
      margin-bottom: 20px;
    }
  }
}
</style>